import { Router } from 'express';
import CONFIG from '../../config';
import logger from '../../util/logger';
import UserService from '../../service/user-service';
import SiteService from '../../service/site-service';
import WeixinAuthorizerService from '../../service/weixin-authorizer-service';
import WeixinQRCodeService from '../../service/weixin-qrcode-service';
const router = Router();
export default router;

/**
 * 验证当前账号是否绑定了公众号
 * @param req
 * @param res
 * @param next
 */
function verifyAccount(req, res, next) {
  (async () => {
    let defaultWeChat = 0;
    let adminId = req.query.adminId;
    let isExist = await UserService.userExist(adminId);
    if (!isExist) {
      defaultWeChat = 1;
      console.info(`当前用户${adminId}未授权绑定，获取默认用户 ${CONFIG.DEFAULT_USERID} 的信息`);
      adminId = CONFIG.DEFAULT_USERID;
    }
    req.query.defaultWeChat = defaultWeChat;
    req.query.adminId = adminId;
    next();
  })();
}

/**
 * 提取全量信息
 */
router.all('/allAuthInfo', verifyAccount, (req, res, next) => {
  (async () => {
    try {
      let { defaultWeChat, adminId } = req.query;
      let result: any, _result: any;
      _result = await SiteService.getAccessTokenInfo();
      let { accessToken, expiresTime } = _result;
      try {
        result = await UserService.getAvailableInfo(adminId);
      } catch (e) {
        console.error(e);
        return res.status(200).json(e);
        // result = await UserService.getAvailableInfo(CONFIG.DEFAULT_USERID);
      }
      let { appId, authExpiresTime, authToken, jsapiTicket, jsapiTicketExpiresTime } = result;

      let authInfo = {
        componentAppId: CONFIG.appID, //平台相关信息
        componentAccessToken: accessToken,
        cpAccessTokenExpiresTime: expiresTime.getTime(),

        appId, //D用户公众号相关信息
        authToken,
        authExpiresTime,
        jsapiTicket,
        jsapiTicketExpiresTime,
        defaultWeChat
      };
      res.status(200).json(authInfo);
    } catch (e) {
      next(e);
    }
  })();
});

/**
 * 提取平台accessTokenInfo
 */
router.all('/accessTokenInfo', (req, res, next) => {
  (async () => {
    try {
      let { accessToken, expiresTime } = await SiteService.getAccessTokenInfo();
      res.status(200).json({ componentAccessToken: accessToken, cpAccessTokenExpiresTime: expiresTime });
    } catch (e) {
      next(e);
    }
  })();
});

/**
 * 提取公众号accessTokenInfo
 */
router.all('/authAccessTokenInfo', verifyAccount, (req, res, next) => {
  (async () => {
    try {
      let { defaultWeChat, adminId } = req.query;
      let result: any;
      try {
        result = await UserService.getAccessTokenInfo(adminId);
      } catch (e) {
        console.error(e);
        return res.status(200).json(e);
      }
      let { authToken, authExpiresTime } = result;
      res.status(200).json({ authToken, authExpiresTime, defaultWeChat });
    } catch (e) {
      next(e);
    }
  })();
});
/**
 * 提取accessTokenInfo
 */
router.all('/jsapiTicketInfo', verifyAccount, (req, res, next) => {
  (async () => {
    try {
      let { defaultWeChat, adminId } = req.query;
      let result: any;
      try {
        result = await UserService.getJSApiTicket(adminId);
      } catch (e) {
        console.error(e);
        return res.status(200).json(e);
      }

      let { jsapiTicket, jsapiTicketExpireAt: jsapiTicketExpiresTime } = result;
      res
        .status(200)
        .json({ jsapiTicket, jsapiTicketExpiresTime: new Date(jsapiTicketExpiresTime).getTime(), defaultWeChat });
    } catch (e) {
      next(e);
    }
  })();
});

/**
 * 获取授权方账号信息的接口
 */
router.all('/authorizerInfo', verifyAccount, (req, res, next) => {
  (async () => {
    let adminId = req.query.adminId;
    let { authorizer_appid } = await UserService.getInfo(adminId);
    let result = null;
    if (authorizer_appid) {
      try {
        result = await WeixinAuthorizerService.getAuthorizerInfo(authorizer_appid);
        res.status(200).json(result);
      } catch (e) {
        next(e);
      }
    }
  })();
});

router.get('/wechatStatus', verifyAccount, (req, res, next) => {
  (async () => {
    try {
      let { defaultWeChat, adminId } = req.query;
      res.status(200).json({
        adminId,
        defaultWeChat
      });
    } catch (e) {
      next(e);
    }
  })();
});

/**
 * 提取参数二维码信息
 */
router.get('/qrcode', verifyAccount, (req, res, next) => {
  (async () => {
    try {
      const paramMap = {
        QR_SCENE: 'scene_id',
        QR_STR_SCENE: 'scene_str',
        QR_LIMIT_SCENE: 'scene_id',
        QR_LIMIT_STR_SCENE: 'scene_str'
      };

      let { adminId, expire_seconds, action_name, scene_id, scene_str } = req.query;
      const access_token = await UserService.getAccessToken(adminId);
      let key = paramMap[action_name];
      let scene = {};
      scene[key] = req.query[key];
      let params = {
        access_token,
        action_name,
        action_info: { scene },
        expire_seconds
      };
      logger.info('请求二维码参数为------>>>>>>', params);
      let result = await WeixinQRCodeService.createQRCode(params);
      logger.info('请求二维码结果为------>>>>>>', result);
      res.status(200).json(result);
    } catch (e) {
      next(e);
    }
  })();
});

// api接口不报错,输出json
router.use((err, req, res, next) => {
  logger.error('请求方法:', req.method, req.originalUrl);
  logger.error('请求参数:', req.method === 'POST' ? req.body : req.query);
  logger.error('错误信息:', err);
  res.json(err);
});
